﻿using HCQ2WebAPI_Logic.Model;
using System.Web.Http;
using System.Net.Http;
using System.Linq;
using System.IO;
using HCQ2_Common.Constant;
using System.Threading.Tasks;
using HCQ2_Model.ViewModel.WebAPI;
using HCQ2_Model;
using System;
using HCQ2WebAPI_Logic.BaseAPIController;
using System.Web;
using System.Collections.Generic;
using HCQ2_Common;
using HCQ2UI_Helper.Session;
using HCQ2_Model.DocModel;
using HCQ2_Model.ViewModel;
using HCQ2_Model.DocModel.APIModel;
using HCQ2_Model.DocModel.APIResultModel;
using System.Net;
using System.Net.Http.Headers;
using HCQ2_Model.DocModel.APIParam;
using HCQ2_Model.APPModel.ParamModel;
using HCQ2_Model.APPModel;
using HCQ2_Model.Pay;
using HCQ2_Model.VR.Model;
using HCQ2WebAPI_Logic.Filters;
using HCQ2_Model.VR.Params;
using HCQ2_Common.Attributes;
using HCQ2_Model.VRDD.OutputDto._20220627;
using HCQ2_Model.VRDD.InputDto._20220627;

namespace HCQ2WebAPI_Logic.DocumentController
{
    /// <summary>
    ///  上传、下载接口
    /// </summary>
    public class SourceAPIController: BaseWeiXinApiLogic
    {
        //****************************************************1.0.1 上传接口（原始版本）*******************************************************
        #region 1.0.0 上传接口（原始带附件） + async Task<WebApiResultJsonModel> uploadVFiles()
        /// <summary>
        ///  1.0 上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiResultJsonModel> uploadVFiles()
        {
            //获取用户编码
            string userid = HttpContext.Current.Request[AuthorityConstant.USER_ID];//用户编码
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(userid)).FirstOrDefault();
            //文件上传路径
            string pathServer = "/uploadFile/VRFile/" + user.user_guid + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            string uploadPath = request.MapPath(request.ApplicationPath + pathServer);
            if (!Directory.Exists(uploadPath))
                Directory.CreateDirectory(uploadPath);
            CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(uploadPath);
            if (provider.FileData.Count > 1)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "一次只能上传一个文件！", null);
            //定义上传文件名称
            string upFileName = string.Empty;
            int file_id, folder_id;
            try
            {
                //上传附件
                await Request.Content.ReadAsMultipartAsync(provider);
                //获取原始文件名称
                foreach (MultipartFileData file in provider.FileData)
                {
                    upFileName = Path.GetFileName(file.LocalFileName);
                    break;
                }
                //判断是否获取到了附件名称
                if (string.IsNullOrEmpty(upFileName))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "附件原始文件名称异常，附件上传失败~", null);
                //获取表单数据
                T_DocumentInfo model = new T_DocumentInfo { create_id = user.user_id, create_name = user.user_name, create_time = DateTime.Now, update_name = user.user_name, update_time = DateTime.Now };
                //判断必填项
                string[] requridColumn = { "folder_num", "file_name", "file_classify", "file_status","folder_id", "folder_limit", "file_money" };
                string[] allKeys = provider.FormData.AllKeys;
                var value = provider.FormData;
                #region 验证必填项是否异常
                foreach(string item in requridColumn)
                {
                    if (!allKeys.Contains(item) || value.GetValues(item).Length <= 0)
                    {
                        if (!string.IsNullOrEmpty(upFileName))
                            File.Delete(uploadPath + upFileName);
                        return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, item + "：字段必填项！", null);
                    }
                }
                #endregion
                //填充必填数据
                folder_id = Helper.ToInt(value.GetValues("folder_id")[0]);//上传到那个目录下
                model.folder_num = value.GetValues("folder_num")[0];
                model.file_name = value.GetValues("file_name")[0];
                model.file_classify = value.GetValues("file_classify")[0];
                model.file_status = Helper.ToInt(value.GetValues("file_status")[0]);
                model.folder_limit = value.GetValues("folder_limit")[0];
                model.file_money = (allKeys.Contains("file_money")) ? Helper.ToDecimal(value.GetValues("file_money")[0]) : 0;
                model.supplier = value.GetValues("supplier")[0];//供应商
                //非必填字段
                if(value.GetValues("folder_author")!=null)
                    model.folder_author = value.GetValues("folder_author")[0];
                if (value.GetValues("folder_phone") != null)
                    model.folder_phone = value.GetValues("folder_phone")[0];
                T_DocumentFolder folder = operateContext.bllSession.T_DocumentFolder.Select(s => s.folder_id.Equals(folder_id)).FirstOrDefault();
                if (folder != null)
                    model.doc_type = folder.folder_name;
                else
                    model.doc_type = "";
                if (value.GetValues("doc_number") != null)
                    model.doc_number = value.GetValues("doc_number")[0];
                if (value.GetValues("alias_name") != null)
                    model.alias_name = (allKeys.Contains("alias_name")) ? value.GetValues("alias_name")[0] : "";
                if (value.GetValues("issue_start") != null)
                    model.issue_start = (allKeys.Contains("issue_start"))? DateTime.ParseExact(value.GetValues("issue_start")[0], "yyyy-MM-dd", new System.Globalization.CultureInfo("zh-CN")) : (DateTime?)null;
                if (value.GetValues("folder_source") != null)
                    model.folder_source = (allKeys.Contains("folder_source")) ? value.GetValues("folder_source")[0]:"";
                if (value.GetValues("file_note") != null)
                    model.file_note = (allKeys.Contains("file_note")) ? value.GetValues("file_note")[0] : "";
                if (value.GetValues("file_size") != null)
                    model.file_size = (allKeys.Contains("file_size")) ? Helper.ToDecimal(value.GetValues("file_size")[0]) : 0;//文档大小
                model.file_type = upFileName.Substring(upFileName.LastIndexOf('.') + 1);//文档类型
                model.attach_url = "~" + pathServer + upFileName;//文件存放路径
                file_id = operateContext.bllSession.T_DocumentInfo.AddDocInfo(model);
                if (file_id > 0)
                {
                    //3.保存文档-节点对应关系
                    operateContext.bllSession.T_DocumentFolderRelation.AddDocFolderRelation(new T_DocumentFolderRelation { file_id = file_id, folder_path = folder?.folder_path, folder_id = folder_id, create_id = user.user_id });
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "上传成功！", file_id);
                }
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "上传失败！", null);
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(upFileName))
                    File.Delete(uploadPath + upFileName);
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, ex.Message, null);
            }
        }
        #endregion

        #region 1.1 获取用户当天已上传数量 + WebApiResultJsonModel GetNodeNum(BaseBaneModel model)
        /// <summary>
        ///  获取用户当天已上传数量
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetNodeNum(UpFileTypeModel model)
        {
            string pageType = string.Empty;
            if (string.IsNullOrEmpty(pageType))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "页面类型传递错误~","");
            int num = operateContext.bllSession.T_DocumentInfo.GetUpNumByUser(SysPermissSession.ChangeIdByGuid(model.userid), pageType);
            return ApiResultJsonModel.Ok("当天上传数量获取成功~", num);
        }
        #endregion

        #region 1.2 获取下拉值 +  WebApiResultJsonModel GetSelectVal(SelectKeyModel model)
        /// <summary>
        ///  获取下拉值
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetSelectVal(SelectKeyModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            List<ResultSelectVal> list = operateContext.bllSession.T_DocumentInfo.GetDocDictByCode(model);
            if (list.Count <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "获取数据为空，或获取数据异常~", "");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "获取下拉成功~", list);
        }
        #endregion

        #region 1.3 上传缩略图Form形式 + async Task<WebApiResultJsonModel> uploadThumbnail()
        /// <summary>
        ///   上传缩略图Form形式
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiResultJsonModel> uploadThumbnail()
        {
            //获取用户编码
            string userid = HttpContext.Current.Request[AuthorityConstant.USER_ID];//用户编码
            int file_type = RequestHelper.GetIntByName("file_type");//展示类别
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(userid)).FirstOrDefault();
            //文件上传路径
            string pathServer = "/uploadFile/VRFile/" + user.user_guid + "/" + DateTime.Now.ToString("yyyyMMdd") + "/Breviary/";
            string uploadPath = request.MapPath(request.ApplicationPath + pathServer);
            if (!Directory.Exists(uploadPath))
                Directory.CreateDirectory(uploadPath);
            CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(uploadPath);
            //定义上传文件名称
            List<string> upFileNames = new List<string>();
            List<string> oldFileNames = new List<string>();
            try
            {
                //上传附件
                await Request.Content.ReadAsMultipartAsync(provider);
                //获取原始文件名称
                foreach (MultipartFileData file in provider.FileData)
                {
                    upFileNames.Add(Path.GetFileName(file.LocalFileName));
                    oldFileNames.Add(file.Headers.ContentDisposition.Name.Replace("\"", string.Empty));
                }                    
                //判断是否获取到了附件名称
                if (upFileNames==null || upFileNames.Count<=0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "缩略图附件原始文件名称异常，附件上传失败~", null);
                //判断必填项
                string[] allKeys = provider.FormData.AllKeys;
                var value = provider.FormData;
                if(!allKeys.Contains("file_id") || value.GetValues("file_id").Length<=0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "素材/作品ID：字段必填项！", null);                
                //填充必填数据
                int file_id = Helper.ToInt(value.GetValues("file_id")[0]), mark = 0;
                //判断file_id是否存在
                int fileCount = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_id.Equals(file_id));
                if (fileCount <= 0)
                {
                    foreach(string item in upFileNames)
                            File.Delete(uploadPath + item);
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "指定的素材/作品file_id异常或后台不存当前作品~", null);
                }                   
                for (int i=0;i<upFileNames.Count;i++)
                {
                    T_DocBagFileRecord record = new T_DocBagFileRecord
                    {
                        file_id = file_id,
                        file_name = oldFileNames[i].ToString(),
                        file_type = file_type,
                        file_url = "~" + pathServer + upFileNames[i].ToString(),//文件存放路径,
                        create_date = DateTime.Now,
                        create_id = user.user_id,
                        create_name = user.user_name
                    };
                    mark = operateContext.bllSession.T_DocBagFileRecord.Add(record);
                }
                if(mark>0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "上传成功！", null);
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "上传失败！", null);
            }
            catch (Exception ex)
            {
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, ex.Message, null);
            }
        }
        #endregion

        #region 1.4 上传缩略图json形式 + WebApiResultJsonModel uploadIntroduce(IntroduceModel model)
        /// <summary>
        ///  上传缩略图json形式
        /// </summary>
        /// <returns></returns>
        [LogNotParameter]
        [HttpPost]
        public WebApiResultJsonModel uploadIntroduce(IntroduceModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            try
            {
                T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.userid)).FirstOrDefault();
                //文件上传路径
                string pathServer = "/uploadFile/VRFile/" + user.user_guid + "/" + DateTime.Now.ToString("yyyyMMdd") + "/Breviary/";
                string uploadPath = request.MapPath(request.ApplicationPath + pathServer);
                if (!Directory.Exists(uploadPath))
                    Directory.CreateDirectory(uploadPath);
                model.picture.ForEach(o =>
                {
                    string picName = Guid.NewGuid().ToString().Replace("-", ""), prefixStr = o.picFile.Split(';')[0].ToString().Split('/')[1];
                    byte[] picByte = Convert.FromBase64String(o.picFile.Split(',')[1]);
                    string tempName = ImageHelper.CreateImageFromBytes(uploadPath, picName, picByte, prefixStr);
                    if (!string.IsNullOrEmpty(tempName))
                        operateContext.bllSession.T_DocBagFileRecord.Add(new T_DocBagFileRecord
                        {
                            file_id = model.file_id,
                            file_name = o.picName,
                            file_type = model.file_type,
                            file_url = "~" + pathServer + picName + "." + prefixStr,//文件存放路径
                            create_date = DateTime.Now,
                            create_id = user.user_id,
                            create_name = user.user_name
                        });
                });
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "上传成功！", null);
            }
            catch (Exception ex)
            {
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, ex.Message, null);
            }
        }
        #endregion

        //****************************************************1.0.2 上传接口（新版本）*******************************************************
        #region 1.0 上传接口（ 新增不带附件）+WebApiResultJsonModel UploadVRFiles()
        /// <summary>
        ///  1.0.1 上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel UploadVRFiles(UploadVRFileModel model)
        {
            ModelState.Remove("folder_id");
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.userid)).FirstOrDefault();
            #region 获取附件类别
            if (string.IsNullOrEmpty(model.good_type) && string.IsNullOrEmpty(model.folder_num))
            {
                if(model.folder_id<=0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商品类别未传递并且folder_id也未传递！", null);
                var page_type = operateContext.bllSession.T_DocumentFolder.FindSingle(s => s.folder_id == model.folder_id)?.page_type;
                if(string.IsNullOrEmpty(page_type))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "folder_id数据无效！", null);
                model.good_type = page_type;
            }
            else
            {
                if (string.IsNullOrEmpty(model.good_type))
                {
                    List<T_SysModule> listModule = operateContext.bllSession.T_SysModule.Select(s => !string.IsNullOrEmpty(s.file_header));
                    if (listModule == null || listModule.Count <= 0)
                        return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商品类别未传递，并且后台也未配置附件类别前缀！", null);
                    foreach (var item in listModule)
                    {
                        if (model.folder_num.IndexOf(item.file_header) == 0)
                        {
                            model.good_type = item.folder_code;
                            continue;
                        }
                    }
                    if (string.IsNullOrEmpty(model.good_type))
                        return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "根据商品编号前置不能确定当前商品类别！", null);
                }
            }
            #endregion
            #region 处理编码
                //string folderNum = model.folder_num;
                //if (string.IsNullOrEmpty(folderNum))
                //{
                //    //前缀
                //    folderNum = operateContext.bllSession.T_SysModule.FindSingle(s => s.folder_code.Equals(model.good_type))?.file_header;
                //    if (string.IsNullOrEmpty(folderNum))
                //        return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "后台模块管理未配置商品前缀编码，不能上传文件！", null);
                //    folderNum = folderNum + DateTime.Now.ToString("yyyyMMddhhmmss");
                //}
            string folderNum = operateContext.bllSession.T_SysModule.FindSingle(s => s.folder_code.Equals(model.good_type))?.file_header;
            //if (string.IsNullOrEmpty(folderNum))
            //    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "后台模块管理未配置商品前缀编码，不能上传文件！", null);
            folderNum = folderNum + DateTime.Now.ToString("yyyyMMddhhmmss");
            if (string.IsNullOrEmpty(model.folder_num))
                model.folder_num = folderNum;
            if (string.IsNullOrEmpty(model.file_classify))
                model.file_classify = "";
            #endregion
            #region 创建文件对象
            //处理宣传地址
            if (string.IsNullOrEmpty(model.spread_url))
            {
                if (model.option_file != null && model.option_file.Count > 0)
                    model.spread_url = model.option_file[0].spread_url;
            }
            T_DocumentFolder query = null;
            if (model.folder_id <= 0)
            {
                query = operateContext.bllSession.T_DocumentFolder.Select(s => s.page_type.Equals(model.good_type) && s.if_sys && s.if_private && !s.if_limit).FirstOrDefault();
                if (query == null)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "后台管理员未配置默认私有目录！", null);
            }
            T_DocumentFolder folder = (query != null) ? query : operateContext.bllSession.T_DocumentFolder.Select(s => s.folder_id.Equals(model.folder_id)).FirstOrDefault();
            T_DocumentInfo file = new T_DocumentInfo
            {
                store_id = model.store_id,
                store_top = model.store_top,
                is_batch = model.is_batch,
                is_mian = model.is_main,
                isEntity = model.is_entity,
                out_link = model.out_link,
                finish_time = model.finish_time,
                unit_code = !string.IsNullOrEmpty(user.unit_code) ? user.unit_code : "",//代码
                org_unit = !string.IsNullOrEmpty(user.user_unit) ? user.user_unit : "",//中文显示
                supplyType = model.supplyType,
                page_type = model.good_type,
                create_id = user.user_id,
                create_name = user.user_name,
                create_time = DateTime.Now,
                update_name = user.user_name,
                update_time = DateTime.Now,
                folder_num = model.folder_num, //folderNum,
                file_code = (string.IsNullOrEmpty(model.file_code)) ? folderNum : model.file_code,
                file_name = model.file_name,
                alias_name = model.alias_name,
                pro_type = model.pro_type,
                folder_author = model.folder_author,
                folder_phone = model.folder_phone,
                file_classify = model.file_classify,
                folder_source = model.folder_source,
                folder_limit = model.folder_limit,
                supplier = model.supplier,
                file_status = model.file_status,
                spread_url = model.spread_url,
                file_note = model.file_note,
                allow_edit = model.allow_edit > 0 ? true : false,
                file_order = model.fileOrder
            };
            #endregion
            if (!string.IsNullOrEmpty(model.issue_start))
                file.issue_start = DateTime.ParseExact(model.issue_start, "yyyy-MM-dd", new System.Globalization.CultureInfo("zh-CN"));
           
            if (folder != null)
                file.doc_type = folder.folder_name;
            else
                file.doc_type = "";
            //素材格式
            if (!string.IsNullOrEmpty(model.mater_type))
                file.mater_type = model.mater_type;
            //单价
            if (model.file_money > 0)
                file.file_money = model.file_money;
            if (model.listPrice != null && model.listPrice.Count > 0)
                file.file_money = model.listPrice[0].ori_price;
            var tempFile = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_code.Equals(file.file_code) && s.file_status != 4 && !s.if_remove);
            if (null != tempFile)
            {
                string tempMessage = string.Empty;
                switch (tempFile.file_status)
                {
                    case 0: tempMessage = "个人私有"; break;
                    case 1: tempMessage = "待审核"; break;
                    case 3: tempMessage = "免费共享"; break;
                    case 5: tempMessage = "已上架"; break;
                    case 6: tempMessage = "审批未通过"; break;
                }
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, $"当前课件代码已在后台存在，状态为：【{tempFile.file_status}】 {tempMessage}，请处理后再上传！", null);
            }
            int file_id = operateContext.bllSession.T_DocumentInfo.AddDocInfo(file);
            if (file_id > 0)
            {
                try
                {
                    if (folder != null)
                        //添加文件，目录对于关系
                        operateContext.bllSession.T_DocumentFolderRelation.Add(new T_DocumentFolderRelation { file_id = file_id, folder_id = folder.folder_id, create_id = user.user_id, folder_path = folder.folder_path });
                    #region 添加附件记录
                    if (model.option_file != null && model.option_file.Count > 0)
                    {
                        foreach (DocFileOption item in model.option_file)
                        {
                            if (item.option_size > 0)
                                item.option_size = item.option_size / 1024;//将最小单位设置为
                            if (!string.IsNullOrEmpty(item.option_url) && item.option_url.Substring(0, 1) != "/")
                                item.option_url = "/" + item.option_url;
                            T_DocFileOptions fileOption = new T_DocFileOptions
                            {
                                file_id = file_id,
                                file_money = item.file_money,
                                option_name = item.option_name,
                                option_type = item.option_type,
                                head_facility = item.head_facility,
                                option_size = item.option_size,
                                option_url = item.option_url,
                                option_plat = item.option_plat,
                                option_note = item.option_note,
                                down_number = 0,
                                service_id = (item.service_id > 0) ? item.service_id.ToString() : "",
                                file_suffix = item.file_suffix,
                                create_date = DateTime.Now
                            };
                            operateContext.bllSession.T_DocFileOptions.Add(fileOption);
                        }
                    }
                    #endregion

                    #region 填充金额列表
                    if (model.listPrice!=null && model.listPrice.Count > 0)
                    {
                        //填充金额列表
                        model.listPrice.ForEach(s =>
                        {
                            operateContext.bllSession.T_VRGoodDisiPrice.Add(new T_VRGoodDisiPrice
                            {
                                op_code = Helper.GetGuid,
                                file_id = file_id,
                                file_code = file.file_code,
                                price_name = s.price_name,
                                op_month = s.op_month,
                                ori_price = s.ori_price
                            });
                        });
                    }
                    #endregion
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "上传成功！", file_id);
                }
                catch (Exception ex)
                {
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, ex.Message, null);
                }
            }
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "上传异常！", null);
        }
        #endregion

        #region 1.1 编辑上传接口（ 新增不带附件）+WebApiResultJsonModel ModifyVRFiles(ModifyVRFileModel model)
        /// <summary>
        ///  编辑上传接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel ModifyVRFiles(ModifyVRFileModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
                T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.userid)).FirstOrDefault();
                T_DocumentInfo file = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_id == model.file_id);
                T_DocumentFolderRelation fileRel = operateContext.bllSession.T_DocumentFolderRelation.FindSingle(s => s.file_id == model.file_id);
                if (file == null)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "素材/作品id异常！", null);
                #region 是否修改代码
                if (!file.file_code.Equals(model.file_code))
                {
                    int mark = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_code.Equals(model.file_code) && s.file_status == 5);
                    if (mark > 0)
                        return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "编辑后的作品代码不允许重复", null);
                }
                #endregion
                #region 是否更新目录id
                if (fileRel.folder_id != model.folder_id)
                {
                    T_DocumentFolder folder = operateContext.bllSession.T_DocumentFolder.FindSingle(s => s.folder_id == model.folder_id);
                    if (folder == null)
                        return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "警告：修改的目录不存在！", null);
                    fileRel.folder_id = folder.folder_id;
                    fileRel.folder_path = folder.folder_path;
                    operateContext.bllSession.T_DocumentFolderRelation.Modify(fileRel, s => s.fr_id == fileRel.fr_id, "folder_id", "folder_path");
                }
                #endregion
                #region 创建文件对象
                T_DocumentInfo tempFile = new T_DocumentInfo
                {
                    is_batch = model.is_batch,
                    doc_number = model.doc_number,
                    store_id = model.store_id,
                    store_top = model.store_top,
                    unit_code = model.unit_code,
                    out_link = model.out_link,
                    file_name = model.file_name,
                    pro_form = model.pro_form,
                    allow_edit = model.allow_edit,
                    update_name = user.user_name,
                    update_time = DateTime.Now,
                    file_note = model.file_note,
                    file_classify = (!string.IsNullOrEmpty(model.file_classify)) ? model.file_classify : "",
                    pro_type = model.pro_type,
                    file_code = model.file_code,
                    alias_name = model.alias_name,
                    folder_limit = model.folder_limit,
                    mater_type = model.mater_type,
                    file_status = model.file_status,
                    supplyType = model.supply_type,
                    is_recommend = model.is_recommend,
                    approve_note = model.Opinion,
                    approve_time = file.approve_time,
                    approve_name = file.approve_name,
                    isEntity = model.isEntity,
                    file_order = model.fileOrder
                };
                if (model.listPrice != null && model.listPrice.Count > 0)
                    file.file_money = model.listPrice.Min(s => s.ori_price);
                else
                    file.file_money = 0;
                if (model.store_id > 0)
                    tempFile.store_id = model.store_id;
                if (string.IsNullOrEmpty(tempFile.unit_code))
                    tempFile.unit_code = file.unit_code;
                #endregion
                #region 判断是否属于审核
                if (file.file_status != tempFile.file_status)
                {
                    tempFile.approve_time = DateTime.Now;
                    tempFile.approve_name = user.user_name;
                }
                #endregion
                //更新
                List<string> li = new List<string> { "file_name", "pro_form", "allow_edit", "update_name", "update_time", "file_note", "file_classify", "pro_type", "file_code", "alias_name", "folder_limit", "mater_type", "file_status", "supplyType", "is_recommend", "approve_note", "approve_time", "approve_name", "out_link", "unit_code", "store_top", "doc_number", "is_batch", "isEntity", "file_order", "file_money" };
                if (model.store_id > 0)
                    li.Add("store_id");
                operateContext.bllSession.T_DocumentInfo.Modify(tempFile, s => s.file_id == model.file_id, li.ToArray());
                //更新价格
                operateContext.bllSession.T_VRGoodDisiPrice.Delete(s => s.file_id == model.file_id);
                if (model.listPrice != null && model.listPrice.Count > 0)
                {
                    //填充金额列表
                    model.listPrice.ForEach(s =>
                    {
                        operateContext.bllSession.T_VRGoodDisiPrice.Add(new T_VRGoodDisiPrice
                        {
                            op_code = Helper.GetGuid,
                            file_id = model.file_id,
                            file_code = file.file_code,
                            price_name = s.price_name,
                            op_month = s.op_month,
                            ori_price = s.ori_price
                        });
                    });
                }else
                    //删除全部金额
                    operateContext.bllSession.T_VRGoodDisiPrice.Delete(s => s.file_id == model.file_id);
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "编辑成功！", "");
            }
            catch (Exception ex)
            {
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, ex.Message, null);
            }
        }
        #endregion

        #region 1.2 删除文件(素材/作品)以及附件 + WebApiResultJsonModel DeleteFileById(FilesModel model)
        /// <summary>
        ///  删除文件
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel<int?> DeleteFileById(FilesModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.userid)).FirstOrDefault();
            //1.0 删除的是否为自己创建的
            int count = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.create_id == user.user_id && s.file_id == model.file_id);
            if (count <= 0)
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Exception, "待删除的文件不存在或者不属于自己创建！", null);
            //1.1 判断是否有被购买过，没有被购买过删除，有被购买过则修改删除标记
            count = operateContext.bllSession.N_OrderCommodityInfo.SelectCount(s => s.file_id == model.file_id);
            if (count > 0)
            {
                operateContext.bllSession.T_DocumentInfo.Modify(new T_DocumentInfo { if_remove = true }, s => s.file_id == model.file_id, "if_remove");
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Ok, "删除成功！", 1);
            }
            else
            {
                //1.1 删除数据
                operateContext.bllSession.T_DocumentInfo.Delete(s => s.file_id == model.file_id);
                //1.2 作品目录关系
                operateContext.bllSession.T_DocumentFolderRelation.Delete(s => s.file_id == model.file_id);
                //1.3 删除附件记录
                operateContext.bllSession.T_DocFileOptions.Delete(s => s.file_id == model.file_id);
                //1.4 缩略图
                var query = operateContext.bllSession.T_DocBagFileRecord.Select(s => s.file_id == model.file_id);
                query.ForEach(o =>
                {
                    if (!string.IsNullOrEmpty(o.file_url) && File.Exists(HttpContext.Current.Server.MapPath(o.file_url)))
                        File.Delete(HttpContext.Current.Server.MapPath(o.file_url));
                });
                operateContext.bllSession.T_DocBagFileRecord.Delete(s => s.file_id == model.file_id);
                return ApiResultJsonModel<int?>.RedirectWebApi(WebResultCode.Ok, "删除成功！", 0);
            }
        }
        #endregion 

        #region 1.3 删除指定附件+ WebApiResultJsonModel DeleteOptionFileById(OptionFilesModel model)
        /// <summary>
        ///  删除附件
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpGet]
        public WebApiResultJsonModel DeleteOptionFileById(OptionFilesModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.userid)).FirstOrDefault();
            T_DocFileOptions options = operateContext.bllSession.T_DocFileOptions.Select(s => s.option_id == model.option_id).FirstOrDefault();
            if (options == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "待删除的附件不存在！", null);
            //判断是否是自己上传的附件
            int count = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.create_id == user.user_id && s.file_id == options.file_id);
            if (count <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "待删除的附件不存在或者不属于自己创建！", null);
            //1.1 判断是否有被购买过，没有被购买过删除，有被购买过则修改删除标记
            count = operateContext.bllSession.T_VROrderDetail.SelectCount(s => s.file_id == options.file_id);
            if (count > 0)
            {
                operateContext.bllSession.T_DocFileOptions.Modify(new T_DocFileOptions { if_remove = true }, s => s.file_id == options.file_id, "if_remove");
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "删除成功！", null);
            }
            //删除记录
            operateContext.bllSession.T_DocFileOptions.Delete(s => s.file_id == options.file_id);
            //删除文件
            //if (!string.IsNullOrEmpty(options.option_url))
            //    File.Delete(request.MapPath(options.option_url));
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "删除成功！", null);
        }
        #endregion 

        #region 1.4 获取文件（素材/作品）附件列表 + WebApiResultJsonModel GetSourceFileList(DocListParam model)
        /// <summary>
        ///  获取文件（素材/作品）附件列表
        ///  自己的或者购买的
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetSourceFileList(FilesModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if(model.file_id<=0 && string.IsNullOrEmpty(model.file_code))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "作品file_id和作品代码file_code不能同时为空！", null);
            T_DocumentInfo file;
            if (model.file_id <= 0)
            {
                file = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_code.Equals(model.file_code) && s.file_status==5 && !s.if_remove);
                if(file == null)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "根据file_code未找到对应的作品对象！", null);
                model.file_id = file.file_id;
            }else
                file= operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_id == model.file_id);
            if (file == null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "温馨提示：当前文件已删除或不存在！", null);
            int user_id = SysPermissSession.ChangeIdByGuid(model.userid);//用户id
            List<T_DocFileOptions> list = new List<T_DocFileOptions>();
            //作品只获取最新的一个
            if (file.page_type.Equals("VRWorks"))
            {
                var query= operateContext.bllSession.T_DocFileOptions.Select(s => s.file_id == model.file_id).OrderByDescending(s => s.create_date).FirstOrDefault();
                if (query != null)
                    list.Add(query);
            }
            else
                list = operateContext.bllSession.T_DocFileOptions.Select(s => s.file_id == model.file_id);
            //string serviceUrl = GetServiceUrl(options.service_id); 
            List<FileOptionsModel> result = new List<FileOptionsModel>();
            list.ForEach(o => {
                result.Add(new FileOptionsModel
                {
                    isEdit = file.allow_edit,
                    option_id = o.option_id,
                    file_id = o.file_id,
                    file_money = o.file_money,
                    head_facility = o.head_facility,
                    option_name = o.option_name,
                    option_type = o.option_type,
                    option_size = o.option_size,
                    down_number = o.down_number,
                    option_url = o.option_url,
                    option_plat = o.option_plat,
                    if_remove = o.if_remove,
                    option_note = o.option_note,
                    service_id = o.service_id,
                    file_suffix = o.file_suffix
                });
            });
            foreach (FileOptionsModel options in result) {
                options.option_url = string.Empty;
                //if (!string.IsNullOrEmpty(options.option_url) && !string.IsNullOrEmpty(options.service_id)) {
                //    string serviceUrl = GetServiceUrl(options.service_id); 
                //    if(!string.IsNullOrEmpty(serviceUrl))
                //        options.option_url = serviceUrl + options.option_url;
                //}
            }
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "获取文档列表成功~", result);
        }
        #endregion

        #region 1.5 删除缩略图+ WebApiResultJsonModel DeleteBagFileById(BagFileRecordModel model)
        /// <summary>
        ///  删除缩略图
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel DeleteBagFileById(BagFileRecordModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            if(model.file_id<=0 && model.bag_id<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception,"error", null);
            int mark;
            if (model.bag_id > 0)
            {
                var query = operateContext.bllSession.T_DocBagFileRecord.FindSingle(s => s.bag_id == model.bag_id);
                if(query==null)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "bag_id error", null);
                //删除缩略图
                if (!string.IsNullOrEmpty(query.file_url) && File.Exists(HttpContext.Current.Server.MapPath(query.file_url)))
                    File.Delete(HttpContext.Current.Server.MapPath(query.file_url));
                mark = operateContext.bllSession.T_DocBagFileRecord.Delete(s => s.bag_id == model.bag_id);
                if (mark > 0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "", null);
            }
            if (model.file_id > 0)
            {
                var query = operateContext.bllSession.T_DocBagFileRecord.Select(s => s.file_id == model.file_id);
                if(query==null || query.Count<=0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "", null);
                query.ForEach(o =>
                {
                    //删除缩略图
                    if (!string.IsNullOrEmpty(o.file_url) && File.Exists(HttpContext.Current.Server.MapPath(o.file_url)))
                        File.Delete(HttpContext.Current.Server.MapPath(o.file_url));
                    operateContext.bllSession.T_DocBagFileRecord.Delete(s => s.bag_id == o.bag_id);
                });
            }
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "", null);
        }
        #endregion 

        private string GetServiceUrl(string service_id)
        {
            if (string.IsNullOrEmpty(service_id))
                return string.Empty;
            T_ItemCode code = operateContext.bllSession.T_ItemCode.FindSingle(s => s.item_code.Equals("docFileService"));
            List<T_ItemCodeMenum> serviceList = null;
            if (null != code)
                serviceList = operateContext.bllSession.T_ItemCodeMenum.Select(s => s.item_id == code.item_id);
            if (null == serviceList || serviceList.Count <= 0)
                return string.Empty;
            return serviceList.Where(s => s.code_name.Equals(service_id)).FirstOrDefault()?.code_value;
        }

        #region 判断能否下载文件
        /// <summary>
        ///  判断能否下载文件
        /// </summary>
        /// <param name="file_id">文件id</param>
        /// <param name="user_id">用户id</param>
        /// <returns></returns>
        private ResultObjModel isDownLoadFile(int file_id,int user_id)
        {
            ResultObjModel obj = new ResultObjModel(false);
            //1.1 判断文件是否存在
            int fileCount = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_id == file_id);
            if (fileCount <= 0)
            {
                obj.message = "温馨提示：当前文件已删除或不存在！";
                return obj;
            }
            //1.2 判断是否是自己创建的
            int myCount = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_id == file_id && s.create_id == user_id);
            //1.3 判断是否属于免费共享文件
            int publicCount = operateContext.bllSession.T_VRGoodDisiPrice.SelectCount(s => s.file_id == file_id && s.ori_price > 0);
            //1.4 判断是否属于别人分享给我的
            bool shareCount = operateContext.bllSession.T_DocumentInfo.ShareFileToUser(file_id, user_id);
            //1.5 判断是否属于购买的
            bool isPay = operateContext.bllSession.T_DocumentInfo.PayCountByFileId(file_id, user_id);
            if (myCount <= 0 && publicCount > 0 && !shareCount && !isPay)
            {
                obj.message = "温馨提示：文件不属于共享也不是您创作的，并且购买已过期或您尚未购买！";
                return obj;
            }
            if (isPay)
                obj.message = "已购买";
            obj.isFinsh = true;
            return obj;
        }
        #endregion

        #region 1.5  新增（素材/作品）附件 + WebApiResultJsonModel AddVRSingleFile(AddVRSingleFileOption model)
        /// <summary>
        ///  新增附件
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel AddVRSingleFile(AddVRSingleFileOption model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = SysPermissSession.ChangeIdByGuid(model.userid);//用户id
            //1.1 判断需要获取的附件文件是否存在
            int fileCount = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_id == model.file_id && s.create_id == user_id);
           if(fileCount<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "温馨提示：文件不存在或者非自己创建的不允许添加附件资源！", null);
            T_DocFileOptions option = new T_DocFileOptions
            {
                file_id = model.file_id,
                option_name = model.option_name,
                option_size = model.option_size,
                option_type = model.option_type,
                option_note = model.option_note,
                option_url = model.option_url,
                option_plat = model.option_plat,
                down_number = 0,
                head_facility = model.head_facility,
                file_money = model.file_money
            };
            int mark = operateContext.bllSession.T_DocFileOptions.Add(option);
            if(mark>0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功添加资源~", "");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "添加资源失败~", "");
        }
        #endregion

        //****************************************************2.0 下载接口*******************************************************
        #region 2.0.1  获取我的素材列表 + WebApiResultJsonModel GetMyVRManagerFile(DocListParam model)
        /// <summary>
        ///  获取我的素材列表
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetMyVRManagerFile(DocListParam model)
        {
            model.docType = "VRManager";
            return GetSourceFile(model);
        }
        #endregion

        #region 2.0.2  获取我的作品列表 + WebApiResultJsonModel GetMyVRWorksFile(DocListParam model)
        /// <summary>
        ///  获取我的作品列表
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetMyVRWorksFile(DocListParam model)
        {
            model.docType = "VRWorks";
            return GetSourceFile(model);
        }
        #endregion

        #region 2.0.3  获取我的组件列表 + WebApiResultJsonModel GetMyVRModuleFile(DocListParam model)
        /// <summary>
        ///  获取我的组件列表
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetMyVRModuleFile(DocListParam model)
        {
            model.docType = "VRModule";
            return GetSourceFile(model);
        }
        #endregion

        #region 2.0  获取我的素材、作品列表 + WebApiResultJsonModel GetSourceFile(DocListParam model)
        /// <summary>
        ///  获取我的素材、作品列表
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetSourceFile(DocListParam model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            //bool mark = false;
            ////1.0 判断folder_id是否有值
            //mark = model.folder_id > 0;
            //if (!mark) mark = !string.IsNullOrEmpty(model.folder_path);
            //if (!mark) mark = !string.IsNullOrEmpty(model.mater_type);            
            //if (!mark)
            //    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "folder_id、folder_path、素材格式 三个字段不能同时为空！", null);
            T_User user;
            if (!string.IsNullOrEmpty(model.userid))
                user = operateContext.bllSession.T_User.FindSingle(s => s.user_guid.Equals(model.userid));
            else if (model.create_id > 0)
                user = operateContext.bllSession.T_User.FindSingle(s => s.user_id == model.create_id);
            else
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "userid、create_id 不能同时为空，必须至少传一个~", null);
            TableModel tModel = operateContext.bllSession.T_DocumentInfo.GetSynchronMyVRData(model, user.user_id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "获取文档列表成功~", tModel);
        }
        #endregion

        #region 2.1  获取文档下载地址 + WebApiResultJsonModel GetSourceFile(DocListParam model)
        /// <summary>
        ///  获取文档列表
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetSourceDownUrl(ViewFileIMG model)
        {
            try
            {
                if (!ModelState.IsValid)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
                int user_id = SysPermissSession.ChangeIdByGuid(model.userid);
                ResultObjModel obj = isDownLoadFile(model.file_id, user_id);
                if (!obj.isFinsh)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, obj.message, null);
                T_DocFileOptions option = operateContext.bllSession.T_DocFileOptions.FindSingle(s => s.file_id == model.file_id && s.option_id == model.option_id);
                if (option == null)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前素材/作品并未上传附件~", "");
                if (string.IsNullOrEmpty(option.option_url))
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "附件下载链接不存在~", "");
                //更新下载次数
                var file = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_id == model.file_id);
                file.down_number += 1;
                operateContext.bllSession.T_DocumentInfo.Modify(file, s => s.file_id == model.file_id, "down_number");
                //添加用户下载记录
                operateContext.bllSession.T_VRUserDownload.Add(new T_VRUserDownload { file_id = model.file_id, page_type = file.page_type, user_guid = model.userid, down_date = DateTime.Now });
                //修改订单状态
                if (!string.IsNullOrEmpty(obj.message))
                    operateContext.bllSession.T_VROrder.ModifyOrderStatus(user_id, model.file_id);
                //处理下载地址
                string serviceUrl = GetServiceUrl(option.service_id), option_url = option.option_url;
                if (!string.IsNullOrEmpty(serviceUrl))
                    option_url = serviceUrl + option.option_url;
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "获取文档列表成功~", option_url);
            }
            catch (Exception e) {
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "获取文档列表异常~", e.Message);
            }
        }
        #endregion

        #region 2.1.1 判断文件是否已购买 + WebApiResultJsonModel VerifyBuy(ViewFileIMG param)
        /// <summary>
        ///  获取文档列表
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel VerifyBuy(ViewFileIMG param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = SysPermissSession.ChangeIdByGuid(param.userid);
            //判断是否为批量购买
            var f = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_id == param.file_id);
            if(f==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前商品后台不存在！", null);
            if (f.is_batch)
            {
                //支持批量购买
                var file = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.store_id == f.store_id && s.is_mian);
                if (file != null)
                    param.file_id = file.file_id;
            }
            ResultObjModel obj = isDownLoadFile(param.file_id, user_id);
            if (!obj.isFinsh)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, obj.message, null);
            PayDocFileOptionsModel result = operateContext.bllSession.T_DocumentInfo.GetBagFileRecord(param.file_id); 
            if(result==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "您已购买过此商品或商品为免费共享，但是当前商品未上传附件信息！", "");
            result.FileImgUrl = result.FileImgUrl.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "您已购买过此商品或商品为免费共享！", result);
        }
        #endregion

        #region 2.1.2 获取文件购买截止日期 + WebApiResultJsonModel VerifyBuy(ViewFileIMG param)
        /// <summary>
        ///  获取文件购买截止日期
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel GetFileEndTime(VRStarView param)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            int user_id = (!string.IsNullOrEmpty(param.userid)) ? SysPermissSession.ChangeIdByGuid(param.userid) : 0;
            PayNorderModel result = operateContext.bllSession.T_DocumentInfo.GetFileEndTime(param.file_id, user_id);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功获取文件购买截止信息！", result);
        }
        #endregion

        #region 2.2  下载附件 + IHttpActionResult DownFileById()
        /// <summary>
        ///  下载附件
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult DownFileById()
        {
            var browser = string.Empty;
            if (HttpContext.Current.Request.UserAgent != null)
                browser = HttpContext.Current.Request.UserAgent.ToUpper();
            string userid = RequestHelper.GetStrByName("userid");//登录用户
            int file_id = RequestHelper.GetIntByName("file_id"),//文件id
                option_id = RequestHelper.GetIntByName("option_id");//附件id
            if (string.IsNullOrEmpty(userid) || file_id <= 0)
                throw new Exception("必传参数异常~");
            int user_id = SysPermissSession.ChangeIdByGuid(userid);
            ResultObjModel obj = isDownLoadFile(file_id, user_id);
            if (!obj.isFinsh)
                throw new Exception(obj.message);
            T_DocFileOptions option = operateContext.bllSession.T_DocFileOptions.Select(s => s.file_id == file_id && s.option_id == option_id).FirstOrDefault();
            if (option == null)
                throw new Exception("下载的文档不存在~");
            if(string.IsNullOrEmpty(option.option_url))
                throw new Exception("附件下载链接为空~");
            string filePath = HttpContext.Current.Server.MapPath(option.option_url);
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            FileStream fileStream = File.OpenRead(filePath);
            httpResponseMessage.Content = new StreamContent(fileStream);
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName =
                    browser.Contains("FIREFOX")
                        ? Path.GetFileName(filePath)
                        : HttpUtility.UrlEncode(Path.GetFileName(filePath))
            };
            return ResponseMessage(httpResponseMessage);
        }
        #endregion 

        #region 2.3  商品上架 + WebApiResultJsonModel PutGoodsOnSale(PutGoodsModel model)
        /// <summary>
        ///  2.3  商品上架
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        [ModelValid]
        public WebApiResultJsonModel PutGoodsOnSale(PutGoodsModel model)
        {
            if (model.fileid <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商品id不能为空！", null);
            int mark = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_id == model.fileid);
            if(mark<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "指定商品不存在！", null);
            mark = operateContext.bllSession.T_DocumentInfo.Modify(new T_DocumentInfo { file_status = 5 }, s => s.file_id == model.fileid, "file_status");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "商品上架成功~", "");
        }
        #endregion

        #region 2.4  更改商品状态 + WebApiResultJsonModel UpdateGoodsStatus(PutGoodsStatus model)
        /// <summary>
        ///  2.4  更改商品状态
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        [ModelValid]
        public WebApiResultJsonModel UpdateGoodsStatus(PutGoodsStatus model)
        {
            if (model.fileid <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "商品id不能为空！", null);
            int mark = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_id == model.fileid);
            if (mark <= 0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "指定商品不存在！", null);
            mark = operateContext.bllSession.T_DocumentInfo.Modify(new T_DocumentInfo { file_status = model.fileStatus }, s => s.file_id == model.fileid, "file_status");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "更新商品状态成功~", "");
        }
        #endregion

        //****************************************************3.0 同步************************************************************
        #region 3.1 上传同步（更新单个附件） + async Task<WebApiResultJsonModel> ModifyUploadVFiles()
        /// <summary>
        ///  上传同步（更新）
        ///  file_id：原始文件ID
        ///  fileUpload：附件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<WebApiResultJsonModel> ModifyUploadVFiles()
        {
            //获取用户编码
            string userid = HttpContext.Current.Request[AuthorityConstant.USER_ID];//用户编码
            T_User user = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(userid)).FirstOrDefault();
            //文件上传路径 
            string pathServer = "/uploadFile/VRFile/" + user.user_guid + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            string uploadPath = request.MapPath(request.ApplicationPath + pathServer);
            if (!Directory.Exists(uploadPath))
                Directory.CreateDirectory(uploadPath);
            CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(uploadPath);
            if (provider.FileData.Count > 1)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "一次只能上传一个文件！", null);
            //定义上传文件名称
            string upFileName = string.Empty;
            try
            {
                //上传附件
                await Request.Content.ReadAsMultipartAsync(provider);
                foreach (MultipartFileData file in provider.FileData)
                {
                    upFileName = Path.GetFileName(file.LocalFileName);
                    break;
                }
                var value = provider.FormData;
                //填充必填数据
                int file_id= Helper.ToInt(value.GetValues("file_id")[0]);
                if (file_id <= 0)
                {
                    if (!string.IsNullOrEmpty(upFileName))
                        File.Delete(uploadPath + upFileName);
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前同步文件不存在~", null);
                }
                T_DocumentInfo info = operateContext.bllSession.T_DocumentInfo.Select(s => s.file_id.Equals(file_id)).FirstOrDefault();
                int mark = operateContext.bllSession.T_DocumentInfo.Modify(new T_DocumentInfo { attach_url = "~" + pathServer + upFileName }, s => s.file_id.Equals(file_id), "attach_url");
                if (mark > 0)
                {
                    //删除原来的记录 
                    if (!string.IsNullOrEmpty(info.attach_url))
                        File.Delete(request.MapPath(info.attach_url));
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "同步更新成功！", null);
                }
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "同步更新失败！", null);
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(upFileName))
                    File.Delete(uploadPath + upFileName);
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, ex.Message, null);
            }
        }
        #endregion

        #region 3.2  更新浏览次数 + WebApiResultJsonModel SynchronBrowseNum(FileSynchronModel model)
        /// <summary>
        ///  更新浏览次数
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel SynchronBrowseNum(FileSynchronModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            var file = operateContext.bllSession.T_DocumentInfo.Select(s => s.file_id == model.file_id).FirstOrDefault();
            if(file==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "当前商品不存在！", null);
            file.browse_num = file.browse_num + 1;
            int mark = operateContext.bllSession.T_DocumentInfo.Modify(file, s => s.file_id == model.file_id, "browse_num");
            if(mark>0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "成功更新浏览次数", "");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "更新浏览次数失败！", "");
        }
        #endregion

        //****************************************************4.0 分享************************************************************
        #region 4.0  分享查询用户 + WebApiResultJsonModel QueryShareUser(ShareUserName model)
        /// <summary>
        ///  分享查询用户
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel QueryShareUser(ShareUserName model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            List<T_User> list = operateContext.bllSession.T_User.Select(s => s.user_name.Contains(model.userName));
            if (list == null ||list.Count<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "查无此人！", null);
            List<ShareUserList> shareUser = new List<ShareUserList>();
            foreach (var item in list)
                shareUser.Add(new ShareUserList { userName = item.user_name, keyId = item.user_guid });
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "查询成功~", shareUser);
        }
        #endregion

        #region 4.0  分享指定素材/作品给某人 + WebApiResultJsonModel DownFileById(DocListParam model)
        /// <summary>
        ///  分享指定素材/作品给某人
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel ShareToUser(ShareToUserModel model)
        {
            if (!ModelState.IsValid)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, getErrorMessage(ModelState), null);
            //被分享人
            T_User beUser = operateContext.bllSession.T_User.Select(s => s.user_guid.Equals(model.keyId)).FirstOrDefault();
            if(beUser==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "被分享人不存在！", null);
            //分享人
            int useID = SysPermissSession.ChangeIdByGuid(model.userid);
            int? beId = beUser.user_id;
            //查询文件是否为我自己上传的
            int myFileCount = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_id.Equals(model.fileId) && s.create_id.Equals(useID));
            if(myFileCount<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "不是自己创作的文档不允许分享！", null);
            List<T_DocumentSetType> typeList = operateContext.bllSession.T_DocumentSetType.Select(s => s.file_id == model.fileId && s.share_id == useID);
            if (typeList.Count > 0)
            {
                int typeCount = typeList.Where(s => s.user_id == beId).Count();
                if(typeCount>0)
                    return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "已被分享过~", "");
            }
            T_DocumentFolderRelation folder = operateContext.bllSession.T_DocumentFolderRelation.Select(s => s.file_id.Equals(model.fileId)).FirstOrDefault();
            int addCount = operateContext.bllSession.T_DocumentSetType.Add(new T_DocumentSetType { file_id = model.fileId, share_id = useID, folder_id = folder.folder_id, user_id = beUser.user_id });
            if(addCount>0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "分享成功~", "");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "分享失败~", "");
        }
        #endregion

        //****************************************************5.0 接口异常********************************************************
        #region 2.1  添加异常接口 + WebApiResultJsonModel AddExceptionLog(T_VRExceptionLog model)
        /// <summary>
        ///  添加异常接口
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public WebApiResultJsonModel AddExceptionLog(T_VRExceptionLog model)
        {
            if(string.IsNullOrEmpty(model.logCode))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "logCode：异常代码不允许为空！", null);
            if (string.IsNullOrEmpty(model.func))
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "func：请求方法不允许为空！", null);
            //判断异常唯一标识是否被占用
            int mark = operateContext.bllSession.T_VRExceptionLog.SelectCount(s => s.logCode.Equals(model.logCode));
            if(mark>0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, $"异常唯一标记：{model.logCode} 已被占用请重新设置！", null);
            //处理请求参数
            if (!string.IsNullOrEmpty(model.@params))
                model.@params = "{\"" + model.@params.Replace("&", "\",\"").Replace("=", "\":\"") + "\"}";
            //相同的方法是否被记录过
            var query = operateContext.bllSession.T_VRExceptionLog.FindSingle(s => s.func.Equals(model.func));
            if (query != null)
            {
                query.logCode = model.logCode;
                query.@params = model.@params;
                query.notes = model.notes;
                query.requestDate = DateTime.Now;
                query.handDate = null;
                query.isSolve = false;
                mark = operateContext.bllSession.T_VRExceptionLog.Modify(query, s => s.logCode.Equals(query.logCode), "logCode", "params", "notes", "requestDate", "handDate", "isSolve");
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, $"异常记录添加成功，异常代码为：{model.logCode}~", model.logCode);
            }
            model.requestDate = DateTime.Now;
            mark = operateContext.bllSession.T_VRExceptionLog.Add(model);
            if(mark>0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, $"异常记录添加成功，异常代码为：{model.logCode}~", model.logCode);
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Error, "异常日志记录添加失败！", null);
        }
        #endregion

        //****************************************************6.0 编辑作品********************************************************
        #region 2.2  修改宣传地址 + WebApiResultJsonModel ModifyVideoUrl(VideoUrlParam model)
        /// <summary>
        ///  修改宣传地址
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        [ModelValid]
        public WebApiResultJsonModel ModifyVideoUrl(VideoUrlParam model)
        {
           if(model.file_id<=0)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "待修改作品id不能为空！", null);
            var query = operateContext.bllSession.T_DocumentInfo.FindSingle(s => s.file_id == model.file_id);
            if(query==null)
                return ApiResultJsonModel.RedirectWebApi(WebResultCode.Exception, "待修改作品不存在！", null);
            query.spread_url = model.spread_url;
            operateContext.bllSession.T_DocumentInfo.Modify(query, s => s.file_id == model.file_id, "spread_url");
            return ApiResultJsonModel.RedirectWebApi(WebResultCode.Ok, "宣传地址修改成功~", "");
        }
        #endregion

        #region 获取数据字典列表
        /// <summary>
        /// 获取数据字典列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        /// <remarks>20220623度度圈需求3.12</remarks>
        [HttpPost]
        [ModelValid]
        public WebApiResultJsonModel<List<OutputGetDataDictList>> GetDataDictList(InputGetDataDictList param)
        {
            List<OutputGetDataDictList> list = operateContext.bllSession.T_ItemCodeMenum.GetDataDictList(param);
            return ApiResultJsonModel<List<OutputGetDataDictList>>.RedirectWebApi(WebResultCode.Ok, "获取成功", list);
        }
        #endregion
    }
}